package com.jg.visitor.filter;

import com.jg.visitor.GlobalConst;
import com.jg.visitor.common.bean.ResponseBean;
import com.jg.visitor.common.bean.ServiceCode;
import com.jg.visitor.common.utils.CheckParamUtils;
import com.jg.visitor.common.utils.LoginHelper;
import com.jg.visitor.common.utils.ResponseUtil;
import com.jg.visitor.controller.dto.UserDTO;
import com.jg.visitor.domain.User;
import com.jg.visitor.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName="LoginFilter",urlPatterns="/*")
@Order(2)
@Slf4j
public class LoginFilter  implements Filter {
    @Resource
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String path = ((HttpServletRequest) servletRequest).getServletPath();

        boolean isNotAllowed = CheckParamUtils.checkUrlLoginNotAllowed(path);

        if(isNotAllowed){

            //先根据token从缓存拿登录用户
            UserDTO userDTO = LoginHelper.getLoginUser();

            //拿不到证明已经过期了没有登录
            if(userDTO == null){
                ResponseUtil.out((HttpServletResponse)servletResponse, ResponseBean.error(ServiceCode.UNAUTHORIZED));
                return;
            }

            //能拿到判断是否需要刷新token进行续期(距离失效时间10分钟时开始续期)
            else{
                LoginHelper.verifyToken(userDTO);
            }
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        log.info("destroy");
    }

}
